/*

This file is part of roomyak.

Copyright (C) 2008 Pixecur Technologies Incorporated (Esotera).
Visit Esotera at http://www.esoteras3.com
 
roomyak is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
 
roomyak is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with roomyak; see the file COPYING.  If not, write to 
Pixecur Technologies, 213-31 Peet Street, St. John's, NL, A1B 3W8. 
 
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
 
 */
package com.datasentinel.util.file;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Rick Power
 *
 */
public class FilenameGeneratorForCopies
{
	private static Pattern filenameAndExtensionPattern = Pattern.compile("^(.*?)\\.?([^\\.]*)$");
	private static Pattern copyOfMatcherPattern = Pattern.compile("^(.*?)( - Copy)(\\s\\d+)*$");

	public static String getNextFileCopyName(String currentName)
	{
		StringBuffer nextFileCopyName = new StringBuffer();
		Matcher filenameAndExtensionMatcher = filenameAndExtensionPattern.matcher(currentName);
		String fileName = "";
		String fileExtension = "";
		if (filenameAndExtensionMatcher.find())
		{
			fileName = filenameAndExtensionMatcher.group(1);
			fileExtension = filenameAndExtensionMatcher.group(2);
			if ("".equals(fileName))
			{
				/*
				 * file did not have an extension so matched whole file on
				 * extension
				 */
				fileName = fileExtension;
				fileExtension = "";
			}
			Matcher copyOfMatcher = copyOfMatcherPattern.matcher(fileName);
			if (copyOfMatcher.find())
			{
				String group1 = copyOfMatcher.group(1);
				String group2 = copyOfMatcher.group(2);
				String group3 = copyOfMatcher.group(3);
				fileName = group1 + group2 + " "
						+ (1 + (null == group3?0:Integer.parseInt(group3.trim())));
			}
			else
			{
				fileName += " - Copy";
			}
		}
		nextFileCopyName.append(fileName);
		if (!"".equals(fileExtension))
		{
			nextFileCopyName.append('.');
			nextFileCopyName.append(fileExtension);
		}
		return nextFileCopyName.toString();
	}
}
